<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>


    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>


      <!-- 表格 -->
      <tree-table
      :data="catelist"
      :columns="columns"
      :selection-type="false"
      :expand-type="false"
      :show-index="true"
      index-text="#"
      border
      class="tree-table"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success"
          v-if="scope.row.cat_deleted === false"
          style="color: green;"
          ></i>
          <i class="el-icon-error"
          v-else
          style="color: red;"
          ></i>
        </template>


        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
          <el-tag type="success" v-else-if=" scope.row.cat_level === 1" size="mini">二级</el-tag>
          <el-tag type="warning" v-else size="mini">三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">

          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeShopById(scope.row.cat_id)">删除</el-button>
        </template>

      </tree-table>

      <!-- 分页 -->
      <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1,5,10,15]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
      </el-pagination>

    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose"
      >
      <!-- 分类表单 -->
      <el-form
      :model="addCateFrom"
      :rules="addCateFromRules"
      ref="addCateFromRef"
      label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateFrom.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级名称:">
          <!-- 级联选择器 -->
          <!-- options  级联选择器的数据源 -->
          <!-- props 配置对象 -->
          <!-- v-model  必须是数组 -->
          <el-cascader
              :options="parentCateList"
              v-model="selectedKeys"
              :props="cascaderProps"
              @change="parentCateChange"
              clearable
              >
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑的对话框 -->
    <el-dialog
      title="修改商品"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
      >
      <el-form
      :model="addShopFrom"
      :rules="addShopFromRules"
      ref="addShopFromRef"
      label-width="100px">
        <el-form-item label="修改商品" prop="cat_name">
          <el-input v-model="addShopFrom.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editShopInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    created(){
      this.getCateList()
    },
    data(){
      return{
        //查询条件(文档参数)
        queryInfo:{
          type:3,
          pagenum:1,
          pagesize:10
        },
        //商品分类的数据列表，默认为空
        catelist:[],
        //总页数
        total:0,
        columns:[
          {label: '分类名称', prop: 'cat_name'},
          {label: '是否有效',
          //自定义模板列
          type:'template',
          //模板列的名称
          template:'isok'},
          {label: '排序',
          //自定义模板列
          type:'template',
          //模板列的名称
          template:'order'},
          {label: '操作',
          //自定义模板列
          type:'template',
          //模板列的名称
          template:'opt'}
        ],
        //添加分类对话框的显示隐藏
        addCateDialogVisible:false,
        //添加分类的表单数据对象
        addCateFrom:{
          //分类名称
          cat_name:'',
          //父级分类的ID
          cat_pid : 0,
          //分类等级
          cat_level : 0
        },
        //分类的表单数据对象的验证规则对象
        addCateFromRules:{
          cat_name:[
            { required: true,
            message: '请输入分类名称',
            trigger: 'blur' }
          ]
        },
        //父级分类的列表
        parentCateList:[],
        //级联选择器的配置对象
        cascaderProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children',
          expandTrigger: 'hover',
          checkStrictly:'true'
        },
        //选中父级分类的ID数组
        selectedKeys: [],
        //控制对话框的显示隐藏
        editDialogVisible:false,
        //添加商品
        addShopFrom:{},
        //添加商品的验证规则
        addShopFromRules:{
          cat_name:[{required: true, message: '请输入修改商品的名称', trigger: 'blur' }]
        }
      }
    },
    methods:{
      //获取商品分类数据
      async getCateList(){
        const {data:res} = await this.$http.get('categories',{params : this.queryInfo})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

        //把数据列表赋值给catelist
        this.catelist = res.data.result
        //把数据的总数赋值给total
        this.total = res.data.total

        // this.$message.success(res.meta.msg)
      },
      //监听 页数 的变化
      handleSizeChange(newPageSize){
        this.queryInfo.pagesize = newPageSize
        this.getCateList()
      },
      //监听 页码 的变化
      handleCurrentChange(newPageNum){
        this.queryInfo.pagenum = newPageNum
        this.getCateList()
      },
      //点击添加分类弹出对话框
      showAddCateDialog(){
        //获取列表数据
        this.getParentCateList()
        //打开对话框
        this.addCateDialogVisible = true
      },
      //获取父级分类的数据列表
      async getParentCateList(){
        const{data:res} = await this.$http.get('categories',{params : { type : 2 }})
        // console.log(res)

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.parentCateList = res.data
        // console.log( this.parentCateList)

      },
      //级联选择器发生改变，触发这个函数
      parentCateChange(){
        console.log(this.selectedKeys)

        //如果 selectedKeys.length > 0 ,证明选择了
        //如果 selectedKeys.length = 0 ,证明没有选择
        if(this.selectedKeys.length > 0){
          this.addCateFrom.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
          this.addCateFrom.cat_level = this.selectedKeys.length
          return
        }else{
          this.addCateFrom.cat_pid  = 0
          this.addCateFrom.cat_level = 0
        }
      },
      //添加新分类
      addCate(){
        this.$refs.addCateFromRef.validate(async vaild => {
          //预验证
          if(!vaild) return
          //预验证通过
          const{data:res} = await this.$http.post('categories',this.addCateFrom)

          if(res.meta.status !== 201 ) return this.$message.error(res.meta.msg)

          this.$message.success(res.meta.msg)
          this.getCateList()
          this.addCateDialogVisible =false
        })
      },
      //监听对话框关闭事件
      addCateDialogClose(){
        this.$refs.addCateFromRef.resetFields()
        this.selectedKeys = []
        this.addCateFrom.cat_pid  = 0
        this.addCateFrom.cat_level = 0
      },
      //点击button弹出编辑用户对话框
      async showEditDialog(id){

        const {data : res } = await this.$http.get(`categories/${id}`)

        if(res.meta.status !== 200 ) return this.$message.error(res.meta.msg)

        this.addShopFrom = res.data

        this.editDialogVisible = true
      },
      //监听对话框的关闭事件
      editDialogClosed(){
        this.$refs.addShopFromRef.resetFields()
      },
      //修改商品信息
      editShopInfo(){
        this.$refs.addShopFromRef.validate(async vaild => {
          if(!vaild) return

          const {data:res}  = await this.$http.put(`categories/${this.addShopFrom.cat_id}`, { cat_name : this.addShopFrom.cat_name})

          if(res.meta.status !== 200 ) return this.$message.error(res.meta.msg)
          console.log(res)
          this.$message.success(res.meta.msg)
          this.getCateList()
          this.editDialogVisible = false
        })
      },
      //根据ID删除用户
      async removeShopById(id){
        //先弹框提示是否删除数据
         const confirm = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).catch( err => err )

        if(confirm !== "confirm") return this.$message.info("已取消删除")
        const {data : res} = await this.$http.delete(`categories/${id}`)

        if(res.meta.status !== 200) return this.$message.error(res.meta.mg)
        
        this.$message.success(res.meta.msg)
        this.getCateList()

      }
    }

  }
</script>

<style lang="less" scoped>

.tree-table{
  margin-top: 15px;
}

.el-cascader{
  width: 100%;
}


</style>
